package com.kudian.restful.controller;

import com.kudian.common.persistence.ResultObj;
import com.kudian.common.utils.DateUtils;
import com.kudian.common.utils.NumberUtils;
import com.kudian.common.utils.StringUtils;
import com.kudian.restful.entity.GoodsType;
import com.kudian.restful.entity.LoginSession;
import com.kudian.restful.entity.Seller;
import com.kudian.restful.service.GoodsTypeService;
import com.kudian.restful.service.LoginSessionService;
import com.kudian.restful.service.MediaResService;
import com.kudian.restful.service.SellerService;
import com.kudian.restful.vo.seller.*;
import com.wordnik.swagger.annotations.ApiOperation;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.sql.Timestamp;
import java.util.Date;
import java.util.List;

/**
 * Created by Administrator on 2016/4/17.
 */
@RestController
@RequestMapping("seller")
public class SellerController {
    private static final Logger logger = Logger.getLogger(SellerController.class);

    @Autowired
    private SellerService sellerService;

    @Autowired
    private LoginSessionService loginSessionService;

    @Autowired
    private GoodsTypeService goodsTypeService;

    @Autowired
    private MediaResService mediaResService;

    @RequestMapping(value = "add", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @ApiOperation(value = "创建商户信息", httpMethod = "POST", notes = "商户信息以json格式传递", response = AddSellerRetVO.class)
    public AddSellerRetVO add(@RequestBody AddSellerVO addSellerVO) {
        AddSellerRetVO o = new AddSellerRetVO();
        if (addSellerVO == null || StringUtils.isBlank(addSellerVO.getAccess_token())) {
            o.setErrcode(9999);
            o.setErrmsg("创建商户信息失败!access_token为空");
            return o;
        }

        try {
            LoginSession ent = loginSessionService.getInfo(addSellerVO.getAccess_token());
            if (ent == null) {
                o.setErrcode(9999);
                o.setErrmsg("access_token已失效!");
                return o;
            }

            QuerySellerVO querySellerVO = new QuerySellerVO();
            querySellerVO.setAccess_token(addSellerVO.getAccess_token());
            List<Seller> ses = sellerService.query(querySellerVO);
            if (ses == null || ses.isEmpty()) {
                Seller entity = new Seller();
                // 将商品大类放到商户信息中
                entity.setGtId(addSellerVO.getGtId());
                entity.setName(addSellerVO.getName());
                entity.setTel(addSellerVO.getTel());
                // 配送时间
                entity.setDeliveryTime(addSellerVO.getDeliveryTime());
                entity.setMobilePhone(addSellerVO.getMobilePhone());

                Date date = new Date();
                Timestamp t = new Timestamp(System.currentTimeMillis());
                entity.setRegTime(t);
                entity.setModifyTime(t);

                // 店铺地址
                entity.setAddress(addSellerVO.getAddress());
                // 是否首次减免
                entity.setIsFirst(addSellerVO.getIsFirst());
                // 首次减免额
                entity.setFirstAmount(addSellerVO.getFirstAmount());
                // 是否满减
                entity.setIsFullMinus(addSellerVO.getIsFullMinus());
                // 满多少
                entity.setFullAmount(addSellerVO.getFullAmount());
                // 减多少
                entity.setMinusAmount(addSellerVO.getMinusAmount());
                // 是否减免运费
                entity.setIsShippingFree(addSellerVO.getIsShippingFree());
                // 运费
                entity.setShippingFee(addSellerVO.getShippingFee());

                // 最低消费在审核后使用
                entity.setMinChange(0.0);
                entity.setIsHoliday(addSellerVO.getIsHoliday());
                entity.setDiscount(addSellerVO.getDiscount());
                entity.setBusLicencePics(addSellerVO.getBusLicencePics());
                entity.setCorporateIcardPics(addSellerVO.getCorporateIcardPics());
                entity.setSellerPics(addSellerVO.getSellerPics());
                // 新建商店
                entity.setSellerStatus((short) 0);
                // 经度
                entity.setLongitudes(null);
                // 纬度
                entity.setLatitudes(null);
                LoginSession ls = loginSessionService.getInfo(addSellerVO.getAccess_token());
                entity.setUserId(ls.getUserId());

                sellerService.save(entity);
                // 失败
                o.setErrcode(0);
                o.setErrmsg("成功创建商户信息成功!");
                o.setSellerId(entity.getSellerId());
            } else {
                // 失败
                o.setErrcode(1200);
                o.setErrmsg("此账号已绑定店铺!");
            }
        } catch (Exception e) {
            // 失败
            o.setErrcode(9999);
            o.setErrmsg("创建商户信息失败!");
            e.printStackTrace();
            logger.error(e);
        }
        return o;
    }

    @RequestMapping(value = "query", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @ApiOperation(value = "取得当前登录用户的商户", httpMethod = "POST", notes = "查询条件以json格式传递", response = QuerySellerRetVO.class)
    public @ResponseBody QuerySellerRetVO query(@RequestBody QuerySellerVO querySellerVO) {
        QuerySellerRetVO o = new QuerySellerRetVO();
        if (querySellerVO == null || StringUtils.isBlank(querySellerVO.getAccess_token())) {
            o.setErrcode(9999);
            o.setErrmsg("查询商户信息失败!access_token为空");
            return o;
        }
        LoginSession ent = loginSessionService.getInfo(querySellerVO.getAccess_token());
        if (ent == null) {
            o.setErrcode(9999);
            o.setErrmsg("access_token已失效!");
            return o;
        }

        try {
            List<Seller> ses = sellerService.query(querySellerVO);
            if (ses != null && !ses.isEmpty()) {
                SellerItemVO item = new SellerItemVO();
                Seller se = ses.get(0);

                item.setSellerId(se.getSellerId());
                item.setGtId(se.getGtId());

                GoodsType gt = goodsTypeService.getInfo(se.getGtId());
                if (gt != null) {
                    item.setGtName(gt.getGtName());
                }
                item.setName(se.getName());
                item.setTel(se.getTel());
                // 配送时间
                item.setDeliveryTime(se.getDeliveryTime());
                item.setMobilePhone(se.getMobilePhone());
                item.setUserId(se.getUserId());
                // TODO 是否返回用户信息

                item.setAddress(se.getAddress());
                if (se.getRegTime() != null) {
                    item.setRegTime(DateUtils.dateFormat(se.getRegTime()));
                }
                if (se.getModifyTime() != null) {
                    item.setModifyTime(DateUtils.dateFormat(se.getRegTime()));
                }
                item.setCorporation(se.getCorporation());
                item.setMinChange(se.getMinChange());
                item.setIsFirst(se.getIsFirst());
                item.setFirstAmount(se.getFirstAmount());
                item.setIsFullMinus(se.getIsFullMinus());
                item.setFullAmount(se.getFullAmount());
                item.setMinusAmount(se.getMinusAmount());
                item.setIsShippingFree(se.getIsShippingFree());
                item.setShippingFee(se.getShippingFee());

                item.setIsHoliday(se.getIsHoliday());
                item.setDiscount(se.getDiscount());

                item.setBusLicencePics(mediaResService.getResUrls(se.getBusLicencePics()));
                item.setCorporateIcardPics(mediaResService.getResUrls(se.getCorporateIcardPics()));
                item.setSellerPics(mediaResService.getResUrls(se.getSellerPics()));

                // 前台转译
                item.setSellerStatus(se.getSellerStatus());

                item.setDeliveryStart(se.getDeliveryStart());
                item.setDeliveryEnd(se.getDeliveryEnd());
                item.setIsopen(se.getIsopen());

                if (se.getLongitudes() == null || se.getLongitudes().doubleValue() == 0) {
                    item.setLongitudes("");
                } else {
                    item.setLongitudes(NumberUtils.toString(se.getLongitudes()));
                }
                if (se.getLatitudes() == null || se.getLatitudes().doubleValue() == 0) {
                    item.setLatitudes("");
                } else {
                    item.setLatitudes(NumberUtils.toString(se.getLatitudes()));
                }
                //item.setLongitudes(se.getLongitudes());
                item.setIsopen(se.getIsopen() == null ? false : se.getIsopen());
                o.setErrcode(0);
                o.setErrmsg("成功查询商户信息");
                o.setItem(item);
            } else {
                o.setErrcode(0);
                o.setErrmsg("此用户暂无商户信息");
            }
        } catch (Exception e) {
            // 失败
            o.setErrcode(9999);
            o.setErrmsg("取得当前登录用户的商户信息失败!");
            e.printStackTrace();
            logger.error(e);
        }
        return o;
    }

    @RequestMapping(value = "update", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @ApiOperation(value = "更新商户信息", httpMethod = "POST", notes = "调用此接口前，先等到商户信息，将信息补充全", response = ResultObj.class)
    public @ResponseBody ResultObj update(@RequestBody UpdateSellerVO updateSellerVO) {
        ResultObj o = new ResultObj();

        if (updateSellerVO == null || StringUtils.isBlank(updateSellerVO.getAccess_token())) {
            o.setErrcode(9999);
            o.setErrmsg("更新商户信息失败!access_token为空");
            return o;
        }

        try {
            LoginSession ent = loginSessionService.getInfo(updateSellerVO.getAccess_token());
            if (ent == null) {
                o.setErrcode(9999);
                o.setErrmsg("access_token已失效!");
                return o;
            }

            sellerService.update(updateSellerVO);
            o.setErrcode(0);
            o.setErrmsg("成功更新商户信息");
        } catch (Exception e) {
            // 失败
            o.setErrcode(9999);
            o.setErrmsg("更新商户信息失败!");
            e.printStackTrace();
            logger.error(e);
        }
        return o;
    }

    @RequestMapping(value = "modify", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @ApiOperation(value = "修改商户提交信息", httpMethod = "POST", notes = "审核不通过，再次提交图片信息", response = ResultObj.class)
    public @ResponseBody ResultObj modify(@RequestBody ModifySellerVO modifySellerVO) {
        ResultObj o = new ResultObj();

        if (modifySellerVO == null || StringUtils.isBlank(modifySellerVO.getAccess_token())) {
            o.setErrcode(9999);
            o.setErrmsg("修改商户提交信息失败!access_token为空");
            return o;
        }
        LoginSession ent = loginSessionService.getInfo(modifySellerVO.getAccess_token());
        if (ent == null) {
            o.setErrcode(9999);
            o.setErrmsg("access_token已失效!");
            return o;
        }

        try {
            sellerService.modify(modifySellerVO);
        } catch (Exception e) {
            // 失败
            o.setErrcode(9999);
            o.setErrmsg("修改商户提交信息失败!");
            e.printStackTrace();
            logger.error(e);
        }
        return o;
    }

    /**
     * 开店
     * @param vo
     * @return
     */
    @RequestMapping(value = "openseller", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @ApiOperation(value = "开店", httpMethod = "POST", notes = "", response = ResultObj.class)
    public @ResponseBody ResultObj openseller(@RequestBody OpenVO vo) {
        ResultObj o = new ResultObj();
        if (vo == null || StringUtils.isBlank(vo.getAccess_token())) {
            o.setErrcode(9999);
            o.setErrmsg("修改商户提交信息失败!access_token为空");
            return o;
        }

        try {
            LoginSession ent = loginSessionService.getInfo(vo.getAccess_token());
            if (ent == null) {
                o.setErrcode(9999);
                o.setErrmsg("access_token已失效!");
                return o;
            }
            sellerService.openseller(vo);
            o.setErrcode(0);
            o.setErrmsg("开店成功!");
        } catch (Exception e) {
            // 失败
            o.setErrcode(9999);
            o.setErrmsg("开店失败!");
            e.printStackTrace();
            logger.error(e);
        }
        return o;
    }

    /**
     * 闭店
     * @param vo
     * @return
     */
    @RequestMapping(value = "closeseller", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @ApiOperation(value = "闭店", httpMethod = "POST", notes = "", response = ResultObj.class)
    public @ResponseBody ResultObj closeseller(@RequestBody CloseVO vo) {
        ResultObj o = new ResultObj();
        if (vo == null || StringUtils.isBlank(vo.getAccess_token())) {
            o.setErrcode(9999);
            o.setErrmsg("修改商户提交信息失败!access_token为空");
            return o;
        }
        LoginSession ent = loginSessionService.getInfo(vo.getAccess_token());
        if (ent == null) {
            o.setErrcode(9999);
            o.setErrmsg("access_token已失效!");
            return o;
        }

        try {
            sellerService.closeseller(vo);
            o.setErrcode(0);
            o.setErrmsg("闭店成功!");
        } catch (Exception e) {
            // 失败
            o.setErrcode(9999);
            o.setErrmsg("闭店失败!");
            e.printStackTrace();
            logger.error(e);
        }
        return o;
    }

    //// -------------------------------------------------------------------- ////
    @RequestMapping(value = "queryByClient", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @ApiOperation(value = "查找附近店铺", httpMethod = "POST", notes = "", response = ClientSellerRetVO.class)
    public ClientSellerRetVO queryByClient(@RequestBody ClientSellerVO vo) {
        ClientSellerRetVO o = new ClientSellerRetVO();
        try {
            if (StringUtils.isBlank(vo.getLatitudes()) || StringUtils.isBlank(vo.getLongitudes())) {
                // 失败
                o.setErrcode(9999);
                o.setErrmsg("请重新定位坐标!");
                return o;
            }
            o.setItems(sellerService.queryByClient(vo));
            o.setErrcode(0);
            o.setErrmsg("取得周边店铺成功!");
        } catch (Exception e) {
            // 失败
            o.setErrcode(9999);
            o.setErrmsg("取得周边店铺失败!");
            e.printStackTrace();
            logger.error(e);
        }
        return o;
    }

    @RequestMapping(value = "queryConditionByClient", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @ApiOperation(value = "查找附近店铺--条件筛选", httpMethod = "POST", notes = "", response = ClientSellerRetVO.class)
    public ClientSellerRetVO queryConditionByClient(@RequestBody ClientSellerConditionVO vo) {
        ClientSellerRetVO o = new ClientSellerRetVO();
        try {
            // TODO 进行条件筛选
            ClientSellerVO v = new ClientSellerVO();
            v.setGtId(vo.getGtId());
            v.setLatitudes(vo.getLatitudes());
            v.setLongitudes(vo.getLongitudes());

            // TODO 进行条件筛选
            o.setItems(sellerService.queryByClient(v));
            o.setErrcode(0);
            o.setErrmsg("取得周边店铺成功!");
        } catch (Exception e) {
            // 失败
            o.setErrcode(9999);
            o.setErrmsg("取得周边店铺失败!");
            e.printStackTrace();
            logger.error(e);
        }
        return o;
    }

    @RequestMapping(value = "details", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @ApiOperation(value = "取得店铺信息", httpMethod = "POST", notes = "游客身份时access_token可以赋值为空", response = ClientSellerRetVO.class)
    public DetailsSellerItemRetVO details(@RequestBody DetailsSellerVO vo) {
        DetailsSellerItemRetVO o = new DetailsSellerItemRetVO();
        try {
            o = this.sellerService.detailsByClient(vo);
            if (o == null) {
                o = new DetailsSellerItemRetVO();
                // 失败
                o.setErrcode(9999);
                o.setErrmsg("取得店铺信息失败!");
                return o;
            }

            o.setErrcode(0);
            o.setErrmsg("取得店铺信息成功!");
        } catch (Exception e) {
            // 失败
            o.setErrcode(9999);
            o.setErrmsg("取得店铺信息失败!");
            e.printStackTrace();
            logger.error(e);
        }
        return o;
    }

    @RequestMapping(value = "getGroupBuy", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @ApiOperation(value = "取得店铺团购信息", httpMethod = "POST", notes = "取得店铺团购信息", response = DetailsQueryGroupBuyRetVO.class)
    public DetailsQueryGroupBuyRetVO getGroupBuy(@RequestBody QueryGroupBuyVO vo) {
        DetailsQueryGroupBuyRetVO o = new DetailsQueryGroupBuyRetVO();
        try {
            o.setItems(this.sellerService.getGroupBuy(vo));
            o.setErrcode(0);
            o.setErrmsg("取得店铺团购信息成功!");
        } catch (Exception e) {
            // 失败
            o.setErrcode(9999);
            o.setErrmsg("取得店铺团购信息失败!");
            e.printStackTrace();
            logger.error(e);
        }
        return o;
    }
}
